<?php if(!defined('BASEPATH')) exit('No direct script access allowed');

require APPPATH . '/libraries/BaseController.php';
/**
 * Class : User (UserController)
 * User Class to control all user related operations.
 * @author : Kishor Mali
 * @version : 1.1
 * @since : 15 November 2016
 */
class Goods extends BaseController
{
    /**
     * This is default constructor of the class
     */
    public function __construct()
    {
        parent::__construct();
        $this->load->model('goods_model');
        $this->isLoggedIn();   
        $this->load->helper(array('form', 'url'));
    }

    public function index($page = 1){
        $number = 10;
        $this->global['pageTitle'] = '亚马逊下单管理';
        $orders = $this->goods_model->getAll($number, ($page - 1) * $number);
        $this->loadViews("goods/goodsList", $this->global, array(
            'error' => ' ',
            'goodsList' => $orders
        ) , NULL);

    }

    public function edit($id = null) {
    	$goods = $this->goods_model->get($id);
    	$this->global['pageTitle'] = isset($goods->id) ? '商品编辑' : '商品新增';
    	$this->loadViews("goods/goodsForm", $this->global, array(
            'error' => ' ',
            'goods' => $goods
        ) , NULL);
    }

    public function save(){
        $goods = $this->input->post('goods');
        $isValid = true;
        foreach ($goods as $key => $value) {
            if(!$value) $isValid = false;
        }
        if($isValid) {
            $this->goods_model->updateOrCreate($goods);
            $this->success('OK');

        } else {
            $this->error(401, '验证失败：每个商品属性都不能为空');            
        }
    }

    public function detail($order_id){
        $order = $this->amazonOrder_model->getOrder($order_id);

        $this->global['pageTitle'] = '亚马逊订单查看';
        $this->loadViews("amazonOrder/orderView", $this->global, array(
            'error' => ' ',
            'details' => $this->createExcelData($order),
            'order' => $order,
            'mergeCells' => '[]'
        ) , NULL);


    }



    public function deleteGoods() {
        $goods_id = $this->input->post('id');
        $this->goods_model->delete($goods_id);
        $this->output
                    ->set_content_type('application/json')
                    ->set_output(json_encode(array('code' => '200', 'message' => $goods_id)));
    }

    public function uploadGoods() {
        $config['upload_path']      = './uploads/';
        $config['allowed_types']    = 'gif|jpg|png|txt|xlsx|xls|csv';
        $config['max_size']     = 1024 * 10;
        $config['max_width']        = 1024 * 10;
        $config['max_height']       = 768 * 10;
        $config['encrypt_name'] = true;

        $this->load->library('upload', $config);
        $this->global['pageTitle'] = 'CodeInsect : Upload';

        if ( ! $this->upload->do_upload('amazonOrderExcel'))
        {
            // 上传失败
            // $error = array('error' => $this->upload->display_errors(), 'upload_data' => $this->upload->data());

            // $this->loadViews('upload/index', $this->global, $error);
            $this->output->set_status_header(400);
        }
        else
        {
            // 上传成功
            try {
                $this->compile_excel($this->upload->data('full_path'));
                $this->output
                    ->set_content_type('application/json')
                    ->set_output(json_encode(array('code' => '200', 'message' => 'OK')));
            } catch(Exception $e) {
                $this->output->set_status_header(400);
            }

            // $data = array('upload_data' => $this->upload->data());
            
            // $this->loadViews('upload/upload_success', $this->global, $data);
        }
    }


    private function compile_excel($file_path) {
        $this->load->library("hei_excel");
        $this->global['pageTitle'] = 'CodeInsect : Excel';
        $option = array(
            'mergeCells' => [],
            'formula' => [],
            'format'=> []
        );
        $data = $this->hei_excel->importExcel($file_path, 0, 0, $option);

        $goodsGroup = array();
        
        foreach (array_values($data) as $key => $value) {
            if($key > 0 && $key < sizeof($data) - 1) {
                $value = array_values($value);
                array_push($goodsGroup, array(
                    'spec_no' => $value[3],
                    'goods_name'  => $value[4],
                    'price' => $value[6],
                    'gift_length'           => $value[8],
                    'gift_width'        => $value[9],
                    'gift_height'              => $value[10],
                    'box_length'          => $value[11],
                    'box_width'             => $value[12],
                    'box_height'             => $value[13],
                    'piece_weight'     => $value[14],
                    'package_weight'       => $value[15],
                    'package_count'      => $value[17]
                ));
            }
                
        }
        $this->goods_model->truncate();
        $this->goods_model->batch($goodsGroup);
        delete_files($file_path);
        return TRUE;
     
    }
    
}

?>